/**
 * Description: 管理员管理
 *
 * @author      Eden
 * @datetime    2016/11/28 16:37
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {
    
    // 显示浮框
    function showCover(type, html) {
        var css = 'tips', dom = $('<div></div>');
        if (type == 'success') {
            css += '  tips-blue';
        } else {
            css += '  tips-red';
        }
        dom.addClass(css);
        dom.html(html);
        $('#avatar-box').append(dom);
    }

    // 隐藏浮框
    function removeCover() {
        var dom = $('#avatar-box').find('.tips');
        dom.fadeOut(3000, function () {
            dom.remove();
        });
    }

    var $ = jQuery, uploader;

    var api = {
        uploadAvatarUrl: '/system/admin/upLoad?type=avatar&extra=backend',
        addUrl: '/system/admin/addAdmin',
        editUrl: '/system/admin/editAdmin',
        deleteUrl: "/admin/user/delete"
    };



    sm.controller('admin-system-admin', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {


        // 初始化数据
        $scope.roles = rolesData;
        $scope.lists = listsData;
        $scope.detail = null;
        $scope.listIndex = null;
        $scope.modalType = '';

        angular.forEach($scope.lists, function (value, key) {
            if (value && value['avatarPaths'] && value['avatarPaths']['b']) {
                $scope.lists[key]['showAvatar'] = value['avatarPaths']['b'];
            }
        });
        
        $scope.delete = function (index) {

            var item = $scope.lists[index];
            if (!item['id']) {
                return false;
            }

            Modal.alert({
                title: "操作提示",
                content: "您确定删除该用户的管理权限吗？",
                buttons: [{
                    name: "取消"
                }, {
                    name: "确定",
                    event: function () {
                        doDelete(index, item.id);
                    }
                }]
            });
        };

        function doDelete(index, id) {
            $http.get(api.deleteUrl, {
                params: {
                    id: id
                }
            }).success(function (res) {
                if (res.state) {
                    Modal.success('操作成功')
                    $scope.lists.splice(index, 1);
                } else {
                    Modal.error(res.error?res.error:'操作失败');
                }
            });
        }


        $scope.editItem = function ($index) {

            // 弹开模态框
            $('#testModal').modal();
            $scope.modalType = 'edit';
            $scope.listIndex = parseInt($index);
            $scope.detail = angular.copy($scope.lists[$index]);

            console.log(111);
            function upload() {
                // 初始化Web Uploader
                console.log(222);
                var uploader = WebUploader.create({
                    auto: true,
                    server: api.uploadAvatarUrl,
                    pick: '#avatarUploader',
                    swf: '/assets/library/webuploader/Uploader.swf',
                    duplicate: true,
                    accept: {
                        title: 'Images',
                        extensions: 'gif,jpg,jpeg,png'
                    }
                });

                // 成功
                uploader.on('uploadSuccess', function(file, res) {
                    if (res.state) {
                        $scope.detail.avatar = res.data.key;
                        $scope.detail.showAvatar = res.data['fullPath'];
                        $scope.$apply();
                        showCover('success', '上传成功');
                    } else {
                        var error = res.error ? res.error : '上传失败';
                        showCover('error', error)
                    }
                });

                uploader.on('uploadComplete', function( file ) {
                    $scope.$apply();
                    delete uploader;
                    upload();
                });

                $('#testModal').off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                    // 初始化$scope.detail
                    $scope.detail = null;
                    $scope.listIndex = null;
                    uploader && delete uploader;
                });

            }
            upload();

        };

        $scope.selectRole = function (index) {
            $scope.detail.roleId = $scope.roles[index]['id'];
            $scope.detail.role = $scope.roles[index]['role'];
        };

        $scope.save = function () {

            // 验证用户名和密码
            var err = false;
            var title, content;
            var detail = $scope.detail;
            var pregExp = new RegExp(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i);

            do {

                if (!detail.nickName || !detail.roleId) {
                    title = '用户信息不完整';
                    content = '请将昵称, 邮箱, 电话, 头像等相关信息填写完整';
                    err = true;
                    break;
                }

                if (!detail.email || (detail.email && !pregExp.test(detail.email))) {
                    title = '邮箱格式错误';
                    err = true;
                    break;
                }

                if ($scope.modalType == 'add' && !detail.password) {
                    title = '请输入密码';
                    err = true;
                    break;
                }

                if (detail.password && (detail.password.length < 6 || detail.password.length > 18)) {
                    title = '密码长度错误';
                    content = '密码不能小于6位且不能超过18位';
                    err = true;
                    break;
                }

                // phone
                if(!detail.phone || (detail.phone && !(/^1(3|4|5|7|8)\d{9}$/.test(detail.phone)))){
                    title = "手机号码有误";
                    err = true;
                    break;
                }

            } while(false);

            if (err) {
                $('#testModal').hide();
                var buttons = [{
                    name: "确定",
                    event: function () {
                        $('#testModal').show();
                    }
                }];
                Modal.alert({title: title, content: content, buttons: buttons});
                return false;
            }

            var datas = {
                nickName: detail.nickName,
                email: detail.email,
                phone: detail.phone,
                roleId: detail.roleId,
                avatar: detail.avatar ? detail.avatar : '',
                showAvatar: detail.showAvatar ? detail.showAvatar : ''
            };

            if (detail.password) {
                datas.password = detail.password;
            }

            if ($scope.modalType == 'edit' && detail.id) {
                // 编辑
                var editData = angular.extend(datas, {id: detail.id});
                $http.post(api.editUrl, editData).success(function (res) {
                    $('#testModal').modal('hide');
                    if (res.state) {
                        $scope.lists[$scope.listIndex] = angular.extend($scope.lists[$scope.listIndex], editData);
                        Modal.success('修改成功');
                    } else {
                        var error = res.error ? res.error : '修改失败';
                        Modal.error(error);
                    }
                });

            } else {
                // 添加
                $http.post(api.addUrl, datas).success(function (res) {
                    $('#testModal').modal('hide');
                    if (res.state) {
                        // Modal.success('添加成功');
                        // 跳转到首页
                        window.location.href = '/system/admin/index';

                    } else {
                        var error = res.error ? res.error : '添加失败';
                        Modal.error(error);
                    }
                });

            }
        };


        // 显示添加用户的模态框
        $scope.showAddModal = function () {
            $scope.modalType = 'add';
            $scope.detail = {};
            $scope.detail['roleId'] = $scope.roles[0]['id'];
            $scope.detail['role'] = $scope.roles[0]['role'];

            $('#testModal').modal();
            // 初始化Web Uploader
            uploader = WebUploader.create({
                auto: true,
                server: api.uploadAvatarUrl,
                swf: '/assets/library/webuploader/Uploader.swf',
                pick: '#avatarUploader',
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png',
                    mimeTypes: 'image/*'
                }
            });

            // =============================================

            // 上传之前
            uploader.off('uploadSuccess').on( 'uploadSuccess', function(file, res) {
                if (res.state) {
                    $scope.detail.showAvatar = res.data.paths['b'];
                    $scope.detail.avatar = res.data.saveName;
                    $scope.$apply();
                    showCover('success', '上传成功');
                } else {
                    var error = res.error ? res.error : '上传失败';
                    showCover('error', error)
                }
            });

            uploader.off('uploadComplete').on( 'uploadComplete', function( file ) {
                removeCover();
            });

            // 文件上传失败，现实上传出错。
            uploader.off('uploadError').on( 'uploadError', function( file ) {
                showCover('error', '上传失败');
                removeCover();
            });

            // ===========end==================================

            $('#testModal').off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                // 初始化$scope.detail
                $scope.detail = null;
            });

        };



    }]);

})();